package de.openlaboratory.elib.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.filefilter.WildcardFileFilter;

import de.openlaboratory.elib.utilities.OpenLabUtilities;

public class LoggingServlet extends HttpServlet
{
	private static final long serialVersionUID = -572812720638407543L;

	private static final String TOMCAT7_LOG_SUBDIR = "logs";
	private static final String TOMCAT7_LOG_STD_PREFIX = "tomcat7-stdout";
	private static final String TOMCAT7_LOG_ERR_PREFIX = "tomcat7-stderr";

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
	{

		PrintWriter out = response.getWriter();

		File logPath = getTomcat7LogPath();

		out.println("<html><body>");

		out.println("<br/>Log path (Tomcat): ");
		out.println(logPath.toString());

		out.println("<pre>");

		File logFile = getTomcat7LogFile(logPath, TOMCAT7_LOG_STD_PREFIX);
		out.println(logFile.toString());
		dumpLogFile(out, logFile);
		
		out.println("</pre><font color=\"red\"><pre>");

		logFile = getTomcat7LogFile(logPath, TOMCAT7_LOG_ERR_PREFIX);
		out.println(logFile.toString());
		dumpLogFile(out, logFile);
		
		out.println("</pre></font></body></html>");
	}

	private void dumpLogFile(PrintWriter out, File logFile)
			throws IOException
	{
		String s;
		FileReader fr = new FileReader(logFile);
		BufferedReader br = new BufferedReader(fr);

		while ((s = br.readLine()) != null)
		{
			out.write(s);
			out.write("\n");
		}
	}

	private File getTomcat7LogPath()
	{
		ServletContext servletContext = getServletContext();
		String contextPath = servletContext.getRealPath(File.separator);
		File rootPath = new File(OpenLabUtilities.goUpInPath(contextPath, 2));
		File logDir = new File(rootPath.toString() + File.separator + TOMCAT7_LOG_SUBDIR);

		return logDir;
	}

	private File getTomcat7LogFile(File logDir, String logFilePattern)
	{
		FileFilter fileFilter = new WildcardFileFilter(logFilePattern + "*");
		File[] files = logDir.listFiles(fileFilter);

		if ((files == null) || (files.length == 0))
		{
			return null;
		}

		File lastFile = files[0];
		for (int i = 1; i < files.length; i++)
		{
			if (lastFile.lastModified() < files[i].lastModified())
			{
				lastFile = files[i];
			}
		}

		return lastFile;
	}
}
